//
//  LocationSensor.m
//  gdemm
//
//  Created by 乔明超 on 16/4/14.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "LocationSensor.h"
#import <CoreLocation/CoreLocation.h>
#import "Location.h"
#import "QRCodeManager.h"
#import "CLLocation+YCLocation.h"
@interface LocationSensor()<CLLocationManagerDelegate>
@property (strong,nonatomic) CLLocationManager *locationMgr;
@property (strong,nonatomic) CLGeocoder *geoceder;
@property (strong,nonatomic) NSMutableArray<OnLocationListenerDelegate> *mListeners;
@property (strong,nonatomic) Location *mLocation;

@end
@implementation LocationSensor
static LocationSensor *_instance;

- (instancetype)init
{
    self = [super init];
    if (self) {
        _mMode = -1;
    }
    return self;
}

#pragma mark 懒加载
- (CLLocationManager *)locationMgr{
    if (_locationMgr == nil) {
        _locationMgr = [[CLLocationManager alloc]init];
        _locationMgr.delegate = self;
        _locationMgr.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    }
    return _locationMgr;
}

- (CLGeocoder *)geoceder{
    if (_geoceder == nil) {
        _geoceder = [[CLGeocoder alloc]init];
    }
    return _geoceder;
}

- (NSMutableArray<OnLocationListenerDelegate> *)mListeners{
    if (_mListeners == nil) {
        _mListeners = [NSMutableArray<OnLocationListenerDelegate> array];
    }
    return _mListeners;
}
+ (instancetype)getInstance{
    if (_instance == nil) {
        _instance = [[LocationSensor alloc]init];
    }
    return _instance;
    
}

/**
 *  从二维码中获取地址
 *
 *  @return 地址
 */
- (NSString *)getAddrFromQrcode{
    _mMode = LOCATION_TYPE_QRCODE;
    QRCodeInfo *info = [[QRCodeManager getInstance]getInQrInfo];
    if (info == nil) {
        return  nil;
    }
    return info.mLocation;
}

/**
 *  添加被监听者
 *
 *  @param listener 被监听者
 */
- (void)registerListener:(id<OnLocationListenerDelegate>)listener{
    if (listener != nil) {
        if (![self.mListeners containsObject:listener]) {
            [self.mListeners addObject:listener];
        }else{
            [self.mListeners removeObject:listener];
            [self.mListeners addObject:listener];
        }
    }
}

/**
 *  移除被监听者
 *
 *  @param listener 被监听者
 */
- (void)unRegisterListener:(id<OnLocationListenerDelegate>)listener{
    if (listener != nil) {
        [self.mListeners removeObject:listener];
    }
}

- (void)destory{
    [self.mListeners removeAllObjects];
    [self.locationMgr stopUpdatingLocation];
    _mLocation = nil;
    _instance = nil;
}

- (void)requestLocationWithMode:(int)mode{
    if (mode == LOCATION_TYPE_GPS) {
        _mMode = LOCATION_TYPE_GPS;
    }else if (mode == LOCATION_TYPE_QRCODE){
        _mMode = LOCATION_TYPE_QRCODE;
        [self getAddrFromQrcode];
    }else{
        _mMode = LOCATION_TYPE_WLAN;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
            [self.locationMgr requestAlwaysAuthorization];
        }else{
            [self.locationMgr startUpdatingLocation];
        }
        [self.locationMgr startUpdatingLocation];
    });
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    [self.locationMgr stopUpdatingLocation];
    CLLocation *origalLocation = [locations lastObject];
    CLLocation *marsLocation = [origalLocation locationMarsFromEarth];
    CLLocation *location = [marsLocation locationBaiduFromMars];
    Location *locationInfo = [[Location alloc]init];
    locationInfo.mLatitude = location.coordinate.latitude;
    locationInfo.mLongitude = location.coordinate.longitude;
    locationInfo.mRadius = location.horizontalAccuracy;
    [self.geoceder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //HRLog(@"反地理编码完成");
        NSMutableString *decription = [NSMutableString string];
        CLPlacemark *placemark = [placemarks firstObject];
        NSDictionary *dic = placemark.addressDictionary;
        NSArray *arr = dic[@"FormattedAddressLines"];
        [decription appendFormat:@"%@",[arr firstObject]];
        [decription appendFormat:@"%@",placemark.name ];
        locationInfo.mAddrDescription = decription;
        locationInfo.mCity = dic[@"City"];
        for (id<OnLocationListenerDelegate> delegate in self.mListeners) {
            [delegate locationSensor:self onReceiveLocation:locationInfo];
        }
    }];
}
@end
